# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2019/1/30
# python-version    : Python 3.7.0
# description       : XML 解析工具

import xml.dom.minidom
from com.articles.microapp.utils.constants import CommonConstants as consts
from com.articles.microapp.utils.string_utils import String
from com.articles.microapp.utils.logger_utils import Logger
from com.articles.microapp.config.config import CONFIG

logger = Logger()
config = CONFIG.config()


class XMLParser(object):
    __dom_tree = None
    __root = None

    def __init__(self, file):
        self.__dom_tree = xml.dom.minidom.parse(file)
        self.__root = self.__dom_tree.documentElement

    def get_sql(self, id, params={}, page=[]):
        """
        根据id获取sql语句，并组装参数 \n
        :param id: SQL ID
        :param params: 待组装参数
        :param page: 分页参数
        :return: str
        """
        sql = ''
        try:
            # select 语句
            dmls = self.__root.getElementsByTagName(consts.SQL_TYPE_SELECT)
            for dml in dmls:
                if dml.hasAttribute('id') and dml.getAttribute('id') == id:
                    sql = str(dml.firstChild.data)
                    param_str = ''
                    for key, value in params.items():
                        param_str += " AND " + str(key) + " like '%" + str(value) + "%'"
                    sql = str.replace(sql, '{{condition}}', param_str)
                    if len(page) > 0:
                        sql += ' LIMIT %d,%d' % (int(page[0]), int(page[1]))
            if String.is_empty(sql):
                # insert 语句
                dmls = self.__root.getElementsByTagName(consts.SQL_TYPE_INSERT)
                for dml in dmls:
                    if dml.hasAttribute('id') and dml.getAttribute('id') == id:
                        sql = str(dml.firstChild.data)
                        try:
                            sql = sql % params
                        except Exception as e:
                            raise Exception('参数个数不匹配，' + e)
            if String.is_empty(sql):
                # update 语句
                dmls = self.__root.getElementsByTagName(consts.SQL_TYPE_UPDATE)
                for dml in dmls:
                    if dml.hasAttribute('id') and dml.getAttribute('id') == id:
                        sql = str(dml.firstChild.data)
                        param_str = ''
                        for param in params.items():
                            param_str += " , " + param[0] + " = '" + param[1] + "' "
                        sql = str.replace(sql, '{{condition}}', param_str)
            if String.is_empty(sql):
                # delete 语句
                dmls = self.__root.getElementsByTagName(consts.SQL_TYPE_DELETE)
                for dml in dmls:
                    if dml.hasAttribute('id') and dml.getAttribute('id') == id:
                        sql = str(dml.firstChild.data)
                        param_str = ''
                        for param in params.items():
                            param_str += " AND " + param[0] + " = '" + param[1] + "' "
                        sql = str.replace(sql, '{{condition}}', param_str)
        except Exception as e:
            logger.error(u'获取SQL异常，%s', e)
        # 打印SQL
        if str(config.get_value(consts.DB_SCTION, consts.DB_SHOW_SQL)).upper() == 'TRUE':
            logger.info(sql)
        return sql


if __name__ == '__main__':
    xml = XMLParser('../dao/remark_dao.xml')
    cmd = xml.get_sql('addLike',params={'objId':'555','userId':'111'})
    print(cmd)
